#include <SDL2/SDL.h>
#include <stdio.h>

#define ERR(msg) do { \
        fprintf(stderr, "%s at %d in %s\n", msg, __LINE__, __FILE__); \
        exit(1); \
    } while (0)

int main(int argc, char **argv)
{
    /* Init */
    if (SDL_Init(SDL_INIT_VIDEO) < 0) ERR(SDL_GetError());

    SDL_Window *win = SDL_CreateWindow("demo1",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        640, 480, SDL_WINDOW_SHOWN);
    if (!win) ERR(SDL_GetError());

    SDL_Renderer *renderer = SDL_CreateRenderer(win, -1,
        SDL_RENDERER_ACCELERATED);
    if (!renderer) ERR(SDL_GetError());

    /* Processing event */
    int running = 1;
    int mx0 = -1, my0 = -1, mx1 = -1, my1 = -1;
    SDL_Event event;
    SDL_Rect rect;
    while (running) {
        while (SDL_PollEvent(&event) != 0) {
            switch (event.type) {
            case SDL_QUIT: 
                running = 0; 
                break;
            case SDL_MOUSEBUTTONUP: 
                mx0 = my0 = mx1 = my1 = -1; 
                break;
            case SDL_MOUSEBUTTONDOWN:
                mx0 = event.button.x; 
                my0 = event.button.y; 
                break;
            case SDL_MOUSEMOTION:
                mx1 = event.motion.x; 
                my1 = event.motion.y; 
                break;
            }
            if (!running) break;

            /* Clear window */
            SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
            SDL_RenderClear(renderer);

            /* Drawing */
            SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
            const unsigned char *keys = SDL_GetKeyboardState(NULL);
            if (keys[SDL_SCANCODE_1]) SDL_RenderDrawPoint(renderer, 10, 10);
            if (keys[SDL_SCANCODE_2]) SDL_RenderDrawLine(renderer, 10, 20, 10, 100);
            if (keys[SDL_SCANCODE_3]) {
                rect.x = 20;  rect.y = 20;
                rect.w = 100; rect.h = 100;
                SDL_RenderFillRect(renderer, &rect);
            }
            if (mx0 != -1) {
                rect.x = mx0;       rect.y = my0;
                rect.w = mx1 - mx0; rect.h = my1 - my0;
                SDL_RenderDrawRect(renderer, &rect);
            }

            /* Update window */
            SDL_RenderPresent(renderer);
        }
    }

    /* Free resource */
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(win);
    SDL_Quit();

    exit(0);
}
